package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.config.PortalConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private static final String NO_NEED_SEND_2_PROTAL = "noNeedSend2Protal";
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private PortalConfig portalConfig;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 先调用统一门户接口添加用户
        String res = addUser2Portal(user);
        JSONObject jsonObject = JSONUtil.parseObj(res);
        Long userId = jsonObject.getLong("data");
        log.info("addUser2Portal userId : {}", userId);
        if (null != userId) {
            return toAjax(userService.insertUser(user));
        } else {
            return error("统一门户新增用户失败");
        }
    }

    private String addUser2Portal(SysUser user) {
        Map<String, Object> params = buildUserParams(user, null);
        params.put("password", user.getPassword());
        params.put("createBy", portalConfig.getAppId());
        Map<String, String> header = HttpUtils.createHeader(params);
        log.info("addUser2Portal params : {}", JSONUtil.toJsonStr(params));
        String res = HttpUtils.doPost(portalConfig.getHost() + "/system/api/user/saveUser", JSONUtil.toJsonStr(params), header);
        log.info("addUser2Portal res : {}", JSONUtil.toJsonStr(res));
        return res;
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());

        SysUser dbUser = userService.selectUserByUserName(user.getUserName());
        // 先调用统一门户接口修改用户
        String res = updateUser2Portal(user, dbUser);
        log.info("updateUser2Portal res : {}", res);
        if (NO_NEED_SEND_2_PROTAL.equals(res)) {
            return toAjax(userService.updateUser(user));
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(res);
            Integer code = jsonObject.getInt("code");
            log.info("updateUser2Portal code : {}", code);
            if (200 == code) {
                return toAjax(userService.updateUser(user));
            } else {
                return error("统一门户修改用户信息失败!");
            }
        }
    }

    private String updateUser2Portal(SysUser user, SysUser dbUser) {
        Map<String, Object> params = buildUserParams(user, dbUser);
        if (params.size() == 1) {
            // 说明只有userName，其他字段都没有修改，不需要调用外部接口
            return NO_NEED_SEND_2_PROTAL;
        } else {
            params.put("updateBy", portalConfig.getAppId());
            Map<String, String> header = HttpUtils.createHeader(params);
            log.info("updateUser2Portal params : {}", JSONUtil.toJsonStr(params));
            return HttpUtils.doPut(portalConfig.getHost() + "/system/api/user/updateUserByName", JSONUtil.toJsonStr(params), header);
        }
    }

    private Map<String, Object> buildUserParams(SysUser user, SysUser dbUser) {
        Map<String, Object> params = new TreeMap<>();
         params.put("userName", user.getUserName());
        if ((dbUser == null || !Objects.equals(user.getNickName(), dbUser.getNickName())) && StringUtils.isNotEmpty(user.getNickName())) {
            params.put("nickName", user.getNickName());
        }
        if ((dbUser == null || !Objects.equals(user.getEmail(), dbUser.getEmail())) && StringUtils.isNotEmpty(user.getEmail())) {
            params.put("email", user.getEmail());
        }
        if ((dbUser == null || !Objects.equals(user.getPhonenumber(), dbUser.getPhonenumber())) && StringUtils.isNotEmpty(user.getPhonenumber())) {
            params.put("phonenumber", user.getPhonenumber());
        }
        if ((dbUser == null || !Objects.equals(user.getSex(), dbUser.getSex())) && StringUtils.isNotEmpty(user.getSex())) {
            params.put("sex", Convert.toStr(user.getSex(), "0"));
        }
        return params;
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }

        for (Long userId : userIds) {
            // 先调用统一门户接口删除用户
            deleteUser2Portal(userId);
        }

        return toAjax(userService.deleteUserByIds(userIds));
    }

    private void deleteUser2Portal(Long userId) {
        Map<String, Object> params = new TreeMap<>();
        SysUser userDetailInfo = userService.selectUserById(userId);
        params.put("userName", userDetailInfo.getUserName());
        params.put("appCode", portalConfig.getAppId());
        Map<String, String> header = HttpUtils.createHeader(params);
        log.info("deleteUser2Portal : {}", JSONUtil.toJsonStr(params));
        String res = HttpUtils.doDelete(portalConfig.getHost() + "/app/api/app/delUser/" + portalConfig.getAppId() + "/userName/" + userDetailInfo.getUserName(), JSONUtil.toJsonStr(params), header);
        log.info(res);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }
}
